package com.example.ec.controller;

import com.example.ssm.model.Book;
import com.example.ssm.model.User;
import com.example.ssm.service.BookService;
import com.example.ssm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
@RequestMapping(value = "user")
public class UserController extends BaseController {

    private UserService userService;
    private BookService bookService;

    public UserController(UserService userService, BookService bookService) {
        this.userService = userService;
        this.bookService = bookService;
    }

    @RequestMapping(value = "signOut", method = RequestMethod.GET)
    private String signOut() {
        session.invalidate();
        return "redirect:/index.jsp";
    }

    @RequestMapping(value = "signUp", method = RequestMethod.POST)
    private String signUp(User user) {
        userService.create(user);
        return "redirect:/index.jsp";
    }

    @RequestMapping(value = "signIn", method = RequestMethod.POST)
    private String signIn(User user) {
        user = userService.queryOne("queryUserByUsernameAndPassword", user);
        if (user == null) {
            request.setAttribute("error", "用户名或密码错误");
            return "/index.jsp";
        }
        session.setAttribute("user", user);
        if (user.getRole() == 0) {
            return "redirect:/home.jsp";
        } else {
            session.setAttribute("users", userService.queryList("queryAllUsers", null));
            List<Book> books = bookService.queryAll();
            session.setAttribute("books",books);
            return "redirect:/book/index.jsp";
        }

    }
}